{-# LANGUAGE RecursiveDo,OverloadedStrings,ScopedTypeVariables,TemplateHaskell,GADTs,DeriveGeneric,FlexibleContexts,RankNTypes #-}
{-# LANGUAGE TypeFamilies#-}
module Main where
import Reflex.Dom
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Monoid
import System.Random
import Data.Functor
import GHC.Generics (Generic)
import Data.ByteString (ByteString)
import Control.Monad
import Control.Monad.IO.Class
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar



main = mainWidgetWithHead head bodyWidget
 where 
  cssAttr url = M.fromList [("href", url),("rel", "stylesheet"),("type", "text/css")]
  head::(MonadWidget t m) => m ()
  head = do
    rNum::Integer <-liftIO $ randomIO
    el "title" $ text "UserCenter"
    --elAttr "link" (cssAttr $ "http://127.0.0.1:8080/static/site.css?v=" <> (T.pack $ show rNum)) blank
    --elAttr "link" (cssAttr   "http://127.0.0.1:8080/static/bootstrap.min.css") blank

bodyWidget::(MonadWidget t m) => m ()
bodyWidget =  do
  globalVar <- liftIO $ newTVarIO (M.fromList [("000" (const "1")),("111" (const "2"))])
  globalE <- liftIO $ readTVarIO globalVar
  curDyn <- holdDyn "空" (globalE M.! "111")
  el "div" $ dynText curDyn
  ev <- button "ClickMe!"
  testWidget globalVar
  pure ()

type EvMap t a = M.Map T.Text (Event t a)

testWidget::(MonadWidget t m) => TVar (EvMap t T.Text) -> m ()
testWidget varGlobal  = do
  curE <- liftIO $ readTVarIO varGlobal
  curDyn <- holdDyn "空" (curE M.! "000")
  ev <- button "二层Button"
  liftIO $ atomically $ modifyTVar varGlobal (M.insert "111" (ev $> "嘿嘿嘿"))
  el "div" $ dynText curDyn


{-
checkBox::(SGMonad m) => Maybe (Bool -> m ()) ->  m ()
checkBox callEvent = do
  (isCheck,setIsCheck) <- useState False
  input_ [type_ "checkBox",onClick $ onCheck] [text $ stext]
 where
   onCheck = do
    setIsCheck (not isCheck)
    callEvent <$> isCheck 

checkBox_ = checkBox Nothing

testPanel = do
    checkBox (dispatch "CheckEvent")
    button [onClick $ dispatch "Submit"] [text  "提交"]
    button [onClick $ dispatch "Refresh"] [text  "刷新"]

textTab::(T.Text -> m ()) -> [(T.Text,m ())] -> m ()
textTab onTabChange ctxList = do


data Model = Model {
  persionName::T.Text,
  isDie::T.Text,
  fuckerList::[T.Text]
}

initModel = do
  registerEvent "CheckEvent" (\x -> put $ m {isDie = x})
  registerEvent "Refresh" refresh
 where
  refresh m = do
    list <- fetchSomeMotherFucker "http://xxx.com/ff/aa/3"
    put $ m {fuckerList = list}
-}